package net.htjs.juc.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class ThreadJoin2 {

    static int r1 = 0;
    static int r2 = 0;

    public static void main(String[] args) {
        test();
    }

    private static void test() {
        Thread thread1 = new Thread(() -> {
            log.info("开始");
            try {
                TimeUnit.SECONDS.sleep(1);
                r1 = 10;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("结束");
        }, "Thread-1");

        Thread thread2 = new Thread(() -> {
            log.info("开始");
            try {
                TimeUnit.SECONDS.sleep(2);
                r2 = 20;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            log.info("结束");
        }, "Thread-2");

        try {
            thread1.start();
            thread2.start();
            long start = System.currentTimeMillis();
            log.info("join begin");
            //等待线程结束后在运行主线程
            thread1.join();
            log.info("Thread 1 join end");
            thread2.join();
            log.info("Thread 2 join end");
            long end = System.currentTimeMillis();
            log.info("r1:{}, r2:{}, cost:{}", r1, r2, end - start);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


}
